using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;

namespace StupidSpaceThing
{
	internal class DataTrain : Unit
	{
		public static new int _ProductionTime = 4000;
		public static new int _ProductionCost = 500;
		public override int ProductionTime { get { return _ProductionTime; } }
		public override int ProductionCost { get { return _ProductionCost; } }
		private bool loaded = false;
		private FactionEntity destination = null;

		public DataTrain(Vector3 position)
			: base(new DataTrainEntity(position)) {
			destination = getDestination();
		}

		public override void Update(RealGameTime gameTime) {
			if( Entity.ScaleFactor == 1 ) {
				float distance = Vector2.Distance(destination.Position2D, Position2D);
				if( destination is Hive ) {
					if( distance < 1 ) {
						loaded = false;
						Faction.Credits += 500;
						destination = getDestination();
						((DataTrainEntity)entity).SetModel(false);
					}
				} else if( destination is TradePortal ) {
					if( distance < 1 ) {
						loaded = true;
						destination = getDestination();
						((DataTrainEntity)entity).SetModel(true);
					}
				}
				ApplyForce(destination.Position2D, 15);
			}
			base.Update(gameTime);
		}

		private FactionEntity getDestination() {
			if( loaded ) {
				return Faction.Hive;
			}
			FactionEntity destination = null;
			float shortestDistance = float.MaxValue;
			foreach( Structure s in Faction.None.Structures ) {
				TradePortal portal = s as TradePortal;				
				if( portal != null ) {
					float curDistance = Vector2.Distance(portal.Position2D, Position2D);
					if( curDistance < shortestDistance ) {
						destination = portal;
						shortestDistance = curDistance;
					}
				}
			}
			return destination;
		}
	}
}
